<template>
  <div style="width: 100%;">
    <h2>车位管理</h2>
    <el-button @click="openAddDialog" style="margin-bottom: 15px">新增车位</el-button>
    <el-button @click="openUseListDialog" style="margin-bottom: 15px">查看车位使用列表</el-button>
    <el-dialog v-model="useListDialogVisible" title="车位使用列表">
      <div v-if="isUseListLoading" class="loading-container">加载中...</div>
      <el-table v-else :data="parkingUseList" stripe>
        <el-table-column prop="id" label="使用记录ID"></el-table-column>
        <el-table-column prop="userId" label="用户ID"></el-table-column>
        <el-table-column prop="carNumber" label="车牌号"></el-table-column>
        <el-table-column prop="parkingId" label="车位ID"></el-table-column>
        <el-table-column prop="useType" label="使用类型"></el-table-column>
        <el-table-column prop="startTime" label="开始时间"></el-table-column>
        <el-table-column prop="endTime" label="结束时间"></el-table-column>
      </el-table>
      <el-pagination
          @size-change="handleUseListSizeChange"
          @current-change="handleUseListCurrentChange"
          :current-page="useListCurrentPage"
          :page-sizes="[10, 20, 30]"
          :page-size="useListPageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="useListTotal"
      >
      </el-pagination>
    </el-dialog>
    <div v-if="isParkingListLoading" class="loading-container">加载中...</div>
    <el-table v-else :data="parkingList" stripe>
      <el-table-column prop="id" label="车位ID"></el-table-column>
      <el-table-column prop="communityId" label="小区 ID"></el-table-column>
      <el-table-column prop="location" label="车位位置"></el-table-column>
      <el-table-column prop="status" label="车位状态"></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button
              @click="() => checkAndDeleteParking(scope.row.id, scope.row.status)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
    >
    </el-pagination>
    <el-dialog v-model="addDialogVisible" title="新增车位">
      <el-form :model="newParkingForm" label-width="100px">
        <el-form-item label="车位位置">
          <el-input v-model="newParkingForm.location"></el-input>
        </el-form-item>
        <el-form-item label="车位状态">
          <el-input v-model="newParkingForm.status"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button @click="addParking">确定</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="editDialogVisible" title="编辑车位">
      <el-form :model="editParkingForm" label-width="100px">
        <el-form-item label="车位位置">
          <el-input v-model="editParkingForm.location"></el-input>
        </el-form-item>
        <el-form-item label="车位状态">
          <el-input v-model="editParkingForm.status"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button @click="updateParking">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

const token = localStorage.getItem("token");
const headers = {
  Authorization: token
};

// 车位列表
const parkingList = ref([]);
const addDialogVisible = ref(false);
const editDialogVisible = ref(false);
const newParkingForm = ref({ location: '', status: '' });
const editParkingForm = ref({ id: null, location: '', status: '' });

// 新增分页相关数据
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const isParkingListLoading = ref(false);

// 车位使用列表分页相关数据
const useListCurrentPage = ref(1);
const useListPageSize = ref(10);
const useListTotal = ref(0);
const isUseListLoading = ref(false);

// 车位使用列表
const parkingUseList = ref([]);
const useListDialogVisible = ref(false);

// 获取车位列表
const getParkingList = async () => {
  isParkingListLoading.value = true;
  try {
    const response = await axios.get('/api/parking/property/page', {
      headers,
      params: {
        current: currentPage.value,
        size: pageSize.value
      }
    });
    if (response.data.code === 200) {
      parkingList.value = response.data.data.records;
      total.value = response.data.data.total;
    } else {
      ElMessage.error(response.data.msg);
    }
  } catch (error) {
    console.error(error);
    ElMessage.error('查询车位信息失败');
  } finally {
    isParkingListLoading.value = false;
  }
};

// 打开新增对话框
const openAddDialog = () => {
  addDialogVisible.value = true;
  newParkingForm.value = { location: '', status: '' };
};

// 新增车位
const addParking = async () => {
  try {
    const response = await axios.post('/api/parking/property', null, {
      headers,
      params: {
        location: newParkingForm.value.location,
        status: newParkingForm.value.status
      }
    });
    if (response.data.code === 200) {
      ElMessage.success('新增车位成功');
      addDialogVisible.value = false;
      getParkingList();
    } else {
      ElMessage.error(response.data.msg);
    }
  } catch (error) {
    console.error(error);
    ElMessage.error('新增车位失败');
  }
};

// 打开编辑对话框
const openEditDialog = (row) => {
  editDialogVisible.value = true;
  editParkingForm.value = { ...row };
};

// 更新车位信息
const updateParking = async () => {
  try {
    const response = await axios.put('/api/parking/property', null, {
      headers,
      params: {
        id: editParkingForm.value.id,
        location: editParkingForm.value.location,
        status: editParkingForm.value.status
      }
    });
    if (response.data.code === 200) {
      ElMessage.success('更新车位成功');
      editDialogVisible.value = false;
      getParkingList();
    } else {
      ElMessage.error(response.data.msg);
    }
  } catch (error) {
    console.error(error);
    ElMessage.error('更新车位失败');
  }
};

// 检查并删除车位
const checkAndDeleteParking = async (id, status) => {
  if (status === '已占用' || status === '已预定') {
    ElMessage.warning('该车位已被占用或预定，无法删除');
    return;
  }
  if (confirm('确定要删除该车位吗？')) {
    try {
      const response = await axios.delete('/api/parking/property', {
        headers,
        params: {
          id: id
        }
      });
      if (response.data.code === 200) {
        ElMessage.success('删除车位成功');
        getParkingList();
      } else {
        ElMessage.error(response.data.msg);
      }
    } catch (error) {
      console.error(error);
      ElMessage.error('删除车位失败');
    }
  }
};

// 处理每页数量变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  getParkingList();
};

// 处理当前页码变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  getParkingList();
};

// 获取车位使用列表
const getParkingUseList = async () => {
  isUseListLoading.value = true;
  try {
    const response = await axios.get('/api/parking-use/property/page', {
      headers,
      params: {
        current: useListCurrentPage.value,
        size: useListPageSize.value
      }
    });
    if (response.data.code === 200) {
      parkingUseList.value = response.data.data.records;
      useListTotal.value = response.data.data.total;
    } else {
      ElMessage.error(response.data.msg);
    }
  } catch (error) {
    console.error(error);
    ElMessage.error('获取车位使用列表失败');
  } finally {
    isUseListLoading.value = false;
  }
};

// 处理车位使用列表每页数量变化
const handleUseListSizeChange = (newSize) => {
  useListPageSize.value = newSize;
  getParkingUseList();
};

// 处理车位使用列表当前页码变化
const handleUseListCurrentChange = (newPage) => {
  useListCurrentPage.value = newPage;
  getParkingUseList();
};

// 打开车位使用对话框
const openUseListDialog = async () => {
  useListCurrentPage.value = 1; // 重置当前页码
  useListPageSize.value = 10; // 重置每页数量
  await getParkingUseList();
  useListDialogVisible.value = true;
};

// 初始化数据
getParkingList();
</script>

<style scoped>
.el-pagination {
  margin-top: 20px;
}
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100px;
  font-size: 16px;
  color: #666;
}
</style>